﻿using NLog;
using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace playwrightJu3.Core
{
    public class Project
    {
        public delegate void ProjectInitializedEventHandler();
        public event ProjectInitializedEventHandler? ProjectInitialized;
        public required string Title { get; set; }
        public required string Location { get; set; }
        public int FileCount { get; set; } = 0;
        public List<string> Files { get; set; } = new List<string>();

        private static Logger logger = LogManager.GetCurrentClassLogger();

        public Project()
        {
            ProjectInitialized += Project_ProjectCreated;
        }
        public void Create()
        {
            Directory.CreateDirectory(Path.Combine(Location, Title));
            logger.Info($"Project Created|Project \"{Title}\" is created in \"{Location}\"");
        }

        public void Open()
        {
            string projectPath = Path.Combine(Location, Title);
            if (Directory.Exists(projectPath))
            {

                ProjectInitialized?.Invoke();
                logger.Info($"Project Opened|{projectPath} is opened as a project.");
            }
        }

        private void Project_ProjectCreated()
        {
            Files = GetFiles(out int fileCount);
            FileCount = fileCount;
            logger.Info($"Project {Title} has {fileCount} files");
        }

        public List<string> GetFiles(out int fileCount)
        {
            string projectPath = Path.Combine(Location, Title);
            if (!Directory.Exists(projectPath))
            {
                throw new DirectoryNotFoundException($"Project directory '{projectPath}' does not exist.");
            }
            var files = Directory.GetFiles(projectPath).Select(Path.GetFileName).ToList();
            fileCount = files.Count;
            return files;
        }
    }
}
